package cn.net.cfss.fgbp.face.manage.controller;

import cn.net.cfss.fgbp.base.controller.BaseController;
import cn.net.cfss.fgbp.base.page.PageData;
import cn.net.cfss.fgbp.base.util.ReturnUtil;
import cn.net.cfss.fgbp.base.util.StringUtils;
import cn.net.cfss.fgbp.face.manage.model.tenant.AddModel;
import cn.net.cfss.fgbp.face.manage.model.tenant.UpdateModel;
import cn.net.cfss.fgbp.face.manage.service.CommService;
import cn.net.cfss.fgbp.face.manage.service.OperationService;
import cn.net.cfss.fgbp.face.manage.vo.BaseParas;
import cn.net.cfss.fgbp.spi.manage.constant.OperationTypeEnum;
import cn.net.cfss.fgbp.spi.manage.constant.TableNameConstant;
import cn.net.cfss.fgbp.spi.manage.constant.YesOrNoEnum;
import cn.net.cfss.fgbp.spi.manage.dto.FscTenantDto;
import cn.net.cfss.fgbp.spi.manage.inte.IFscTenantService;
import cn.net.cfss.fgbp.spi.manage.vo.FscTenantVo;
import cn.net.cfss.fgbp.spi.manage.vo.ResultDto;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wutao
 * @version 1.0
 * @date 2020/9/4 15:15
 */
@Api(value = "tenant",tags = {"tenant"})
@RestController
@RequestMapping("/tenant")
@Slf4j
public class TenantController extends BaseController {

    @Autowired
    private IFscTenantService fscTenantService;

    @Autowired
    private CommService commService;

    @Autowired
    private OperationService operationService;


    @ApiOperation("租户管理接口-分页接口")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public String eslPage (@RequestBody BaseParas<PageData<FscTenantVo>> baseParas) {
        try {

            PageData<FscTenantVo> page = fscTenantService.page(baseParas.getPlain());

            return ReturnUtil.returnSucc(page, page.getRows());
        } catch (Exception e) {
            log.error("租户管理接口-分页接口异常：{},请求数据:{}", ExceptionUtils.getStackTrace(e), JSONObject.toJSONString(baseParas));
            return ReturnUtil.returnErr( "操作异常");
        }
    }

    @ApiOperation("租户管理接口-新增接口")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@RequestBody BaseParas<AddModel> baseParas) {
        try {
            AddModel plain = baseParas.getPlain();
            FscTenantVo fscTenantVo = new FscTenantVo();
            BeanUtils.copyProperties(plain, fscTenantVo);
            fscTenantVo.setCreateBy(getUserId());
            fscTenantVo.setUpdateBy(getUserId());

            ResultDto<FscTenantVo> add = fscTenantService.add(fscTenantVo);
            if (!add.getSucc() ) {
                return ReturnUtil.returnErr(add.getErrMsg());
            }

            //记录操作日志
            JSONObject newData = new JSONObject();
            newData.put(TableNameConstant.T_FSC_TENANT, add.getObject());
            String opRemark = "新增租户";
            operationService.addOperationLog(OperationTypeEnum.ADD, opRemark, null, newData.toJSONString());

        } catch (Exception e) {
            log.error("租户管理接口-新增接口异常:{},请求参数：{}", ExceptionUtils.getStackTrace(e), JSONObject.toJSONString(baseParas));
            return ReturnUtil.returnErr("操作异常");
        }
        return ReturnUtil.returnSucc();
    }



    @ApiOperation("租户管理接口-修改接口")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(@RequestBody BaseParas<UpdateModel> baseParas) {
        try {

            UpdateModel plain = baseParas.getPlain();
            FscTenantVo fscTenantVo = new FscTenantVo();
            BeanUtils.copyProperties(plain, fscTenantVo);
            fscTenantVo.setUpdateBy(getUserId());

            FscTenantDto search = new FscTenantDto();
            search.setId(plain.getId());
            FscTenantDto fscTenantDto = fscTenantService.selectOne(search);
            JSONObject oldData = new JSONObject();
            oldData.put(TableNameConstant.T_FSC_TENANT, fscTenantDto);

            ResultDto<FscTenantVo> update = fscTenantService.update(fscTenantVo);
            if (!update.getSucc() ) {
                return ReturnUtil.returnErr(update.getErrMsg());
            }

            //记录操作日志
            String opRemark = "修改租户";
            JSONObject newData = new JSONObject();
            fscTenantDto = fscTenantService.selectOne(search);
            newData.put(TableNameConstant.T_FSC_TENANT, fscTenantDto);
            operationService.addOperationLog(OperationTypeEnum.UPDATE, opRemark, oldData.toJSONString(), newData.toJSONString());
        } catch (Exception e) {
            log.error("租户管理接口-修改接口异常:{},请求参数：{}", ExceptionUtils.getStackTrace(e), JSONObject.toJSONString(baseParas));
            return ReturnUtil.returnErr("操作异常");
        }
        return ReturnUtil.returnSucc();
    }

    @ApiOperation("租户管理-线路预警配置")
    @RequestMapping(value = "/updateLineErrMaxSize", method = RequestMethod.POST)
    public String updateLineErrMaxSize(@RequestBody BaseParas<FscTenantDto> baseParas) {
        try {

            String errMsg = checkUpdateLineErrMaxSize(baseParas.getPlain());
            if (!StringUtils.isEmpty(errMsg)) {
                return ReturnUtil.returnErr(errMsg);
            }

            FscTenantVo updateVo = new FscTenantVo();
            updateVo.setId(baseParas.getPlain().getId());
            updateVo.setEarlyWarnFlag(baseParas.getPlain().getEarlyWarnFlag());
            updateVo.setLineErrMaxSize(baseParas.getPlain().getLineErrMaxSize());
            ResultDto<FscTenantVo> update = fscTenantService.update(updateVo);
            if (update.getSucc()) {
                return ReturnUtil.returnSucc();
            } else {
                return ReturnUtil.returnErr(update.getErrMsg());
            }

        } catch (Exception e) {
            log.error("租户管理-线路预警配置接口异常:{},请求参数：{}", ExceptionUtils.getStackTrace(e), JSONObject.toJSONString(baseParas));
            return ReturnUtil.returnErr("操作异常");
        }

    }

    private String checkUpdateLineErrMaxSize(FscTenantDto plain) {
        if (plain.getId() == null) {
            return "租户id必传";
        }
        if (plain.getEarlyWarnFlag() == null) {
            return "警告标示必传";
        }
        if (YesOrNoEnum.YES.equals(plain.getEarlyWarnFlag())) {
            if (plain.getLineErrMaxSize() == null) {
                return "预警次数必填";
            }
        }
        return null;

    }

    @ApiOperation("租户管理接口-列表（用于下拉框等）")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public String list(@RequestBody BaseParas<FscTenantVo> baseParas) {
        try {
            FscTenantVo fscTenantVo = baseParas.getPlain();
            List<FscTenantVo> list = fscTenantService.list(fscTenantVo);

            //判断权限，是否是租户管理员或者业务员
            Long tenantId = commService.tenantId(request);
            if (tenantId == null) {
                return ReturnUtil.returnSucc(list);
            }

            List<FscTenantVo> result = new ArrayList<>();
            for (FscTenantVo tenantVo : list) {
                if (tenantVo.getId().equals(tenantId)) {
                    result.add(tenantVo);
                }
            }
            return ReturnUtil.returnSucc(result);


        } catch (Exception e) {
            log.error("租户管理接口-列表（用于下拉框等）异常:{},请求参数：{}", ExceptionUtils.getStackTrace(e), JSONObject.toJSONString(baseParas));
            return ReturnUtil.returnErr("操作异常");
        }
    }
}
